var request = {
QueryString : function(val) {
var uri = window.location.search;
var re = new RegExp("" +val+ "\=([^\&\?]*)", "ig");
return ((uri.match(re))?(uri.match(re)[0].substr(val.length+1)):null);
 },
 QueryStrings : function() {
 var uri = window.location.search;
 var re = /\w*\=([^\&\?]*)/ig;
 var retval=[];
 while ((arr = re.exec(uri)) != null)
 retval.push(arr[0]);
 return retval;
 },
 setQuery : function(val1, val2) {
 var a = this.QueryStrings();
 var retval = "";
 var seted = false;
 var re = new RegExp("^" +val1+ "\=([^\&\?]*)$", "ig");
  for(var i=0; i<a.length; i++) {
 if (re.test(a[i])) {
 seted = true;
 a[i] = val1 +"="+ val2;
 }
 }
 retval = a.join("&");
 return "?" +retval+ (seted ? "" : (retval ? "&" : "") +val1+ "=" +val2);
 }
}

var previousPoint = null;
var query = request.QueryString("query");
var start = request.QueryString("start");
var num = request.QueryString("num");
var clusterIndex = request.QueryString("clusterIndex");
var isNewSearch = request.QueryString("isNewSearch");
//var date = request.QueryString("date");
var plot = null;
var dataindex = 0;

$(document).ready(function(){
//    searchonload();
    if(query==null){
    	window.location="http://www.se6.eud.cn";
    }
    var urlQuery = "query=" + query;
    if(start!=null){
    	urlQuery += "&start=" + start;
    }
    if(num!=null){
    	urlQuery += "&num=" + num;
    }
    if(clusterIndex!=null){
    	urlQuery += "&clusterIndex=" + clusterIndex;
    }
    if(isNewSearch!=null){
    	urlQuery += "&isNewSearch=" + isNewSearch;
    }
    $.get("servlet/GetDetails",urlQuery,readyPage1);
});

function readyPage1(data,status){
	//$.get("servlet/GetDate","query=" + query + "&prequery=" + prequery + "&date=" + date,showGram);
	$.get("servlet/GetClusters",null,showClusters);
    showDetails(data);
}

function showDetails(data) {
    var details = eval('(('+data+'))');
//	var details = {"HitsLength":44395,"CostTime":456,"Start":0,"Details":[{"WorkerName":"华南木棉","URL":"http://www.ipv6.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"华南理工大学IPv6","Summary":"&#21326;&#21335;&#29702;&#24037;&#22823;&#23398;IPv6 &#21326;&#21335;&#29702;&#24037;&#22823;&#23398;IPv6&#39547;&#22320;&#32593;&#24050;&#23436;&#25104;&#25903;&#25345;IPv6&#20027;&#24178;&#32593;<span class=\\\"ellipsis\\\"> ... <\/span>&#32476;&#12289;&#21335;&#21271;&#26657;&#21306;&#25509;&#20837;&#32593;&#24314;&#35774;&#24182;&#23454;&#29616;&#37197;&#22871;&#30340;&#26426;&#25151;&#21644;&#30005;&#28304;&#31561;&#20445;&#38556;&#29615;&#22659;<span class=\\\"ellipsis\\\"> ... <\/span>&nbsp;&nbsp;&#29256;&#26435;&#25152;&#26377;&#65306;&#21326;&#21335;&#29702;&#24037;&#22823;&#23398;&#20449;&#24687;&#32593;&#32476;&#24037;&#31243;&#30740;&#31350;&#20013;&#24515;<span class=\\\"ellipsis\\\"> ... <\/span>"},{"WorkerName":"华南木棉","URL":"http://cgsp.scut.edu.cn/CGSPPortal/loginerror.jsp","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"尚未登录","Summary":"&#23578;&#26410;&#30331;&#24405; &#35831;&#20808;&#30331;&#24405;&#20877;&#20351;&#29992;&#65292;&#25110;&#35831;&#32852;&#31995;&#32593;&#26684;&#31649;&#29702;&#21592;&#12290;<span class=\\\"ellipsis\\\"> ... <\/span>"},{"WorkerName":"华南木棉","URL":"http://biogrid.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"生物信息网格平台","Summary":""},{"WorkerName":"华南木棉","URL":"http://cgsp.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"中国教育科研网格","Summary":""},{"WorkerName":"华南木棉","URL":"http://scutgrid11.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"生物信息网格平台","Summary":""},{"WorkerName":"华南木棉","URL":"http://xc.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"xc","Summary":""},{"WorkerName":"华南木棉","URL":"http://biogrid.scut.edu.cn/srs71/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"SRS","Summary":""},{"WorkerName":"华南木棉","URL":"http://search.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"木棉检索","Summary":"&#26408;&#26825;&#26816;&#32034; &nbsp; &nbsp; &#26657;&#20869;&#26816;&#32034; &#26657;&#20869;&#26816;&#32034; &#23376;&#31449;&#26816;&#32034; &#23376;&#31449;&#26816;&#32034;<span class=\\\"ellipsis\\\"> ... <\/span>&#22806;&#35821;&#23398;&#38498; &#24314;&#31569;&#23398;&#38498; &#21326;&#24037;&#26032;&#38395;&#32593; &#30005;&#21147;&#23398;&#38498; &#27861;&#23398;&#38498;<span class=\\\"ellipsis\\\"> ... <\/span>&#26426;&#26800;&#23398;&#38498; &#26426;&#26800;&#19982;&#27773;&#36710;&#23398;&#38498; &#22269;&#38469;&#25945;&#32946;&#23398;&#38498;&#20013;&#25991;&#29256; &#27861;&#24459;&#26041;&#27861;&#19982;&#27861;&#24459;&#24605;&#32500;<span class=\\\"ellipsis\\\"> ... <\/span>"},{"WorkerName":"华南木棉","URL":"http://bcg.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"http://bcg.scut.edu.cn/","Summary":""},{"WorkerName":"华南木棉","URL":"http://biogrid.scut.edu.cn/","WorkerURL":"http://compute-0-5.local:8002/worker?wsdl","Title":"»ªÄÏÀí¹¤´óÑ§ÉúÎïÐÅÏ¢Æ½Ì¨","Summary":"&raquo;&ordf;&Auml;&Iuml;&Agrave;&iacute;&sup1;&curren;&acute;&oacute;&Ntilde;&sect;&Eacute;&uacute;&Icirc;&iuml;&ETH;&Aring;&Iuml;&cent;&AElig;&frac12;&Igrave;&uml;<span class=\\\"ellipsis\\\"> ... <\/span>"}],"ClusterIndex":-1}
    var hitsLength = details.HitsLength;
    if (hitsLength == 0) {
        $("#detailsShow").html("抱歉，没有找到与你的查询相关的网页。 ");
    } else {
        var detailsShow = "";
        var pageIndexShow = "";
        var costTimeShow = "";
        var clusterIndex = details.ClusterIndex;
		var start = details.Start;
        var detailsresult = details.Details;
        var costTime = details.CostTime;
        if(clusterIndex=="-1"){
        	costTimeShow = "共获得"+ hitsLength +"个结果，用时" + costTime + "ms，以下是第";
        }
        else{
        	costTimeShow = "第"+clusterIndex+"个类别，共"+ hitsLength +"个结果，以下是第";
        }
    	costTimeShow += (start+1)+"到第"+(start+detailsresult.length)+"条结果"
    	$("#costTimeShow").html(costTimeShow);
    	
        for (var i = 0; i < detailsresult.length; i+=1) {
            var title = detailsresult[i].Title;
            var url = detailsresult[i].URL;
            var urlDisp = (url.length>80)?url.substring(0,75)+ "...":url;
            var summary = detailsresult[i].Summary;
            var workerName = detailsresult[i].WorkerName;
            var workerURL = detailsresult[i].WorkerURL;
            var indexID = detailsresult[i].IndexID;
            var docID = detailsresult[i].DocID;
            var id = "url=" + url + "&title=" + title + "&idx=" + indexID + "&id=" + docID + "&workerUrl=" + workerURL;
            detailsShow += "<li><h3><a target='_blank' href='"+url+"'>"+title;
            detailsShow += "</a></h3><div id='summary2'><p>"+summary+"</p></div>";
            detailsShow += "<p class='s'><span class='l'>"+urlDisp+"</span> - 结果来自:<span class='highlight'>"+workerName+"</span> - <a target='_blank' href='./cached.jsp?'"+id+" id='snapshotLink2'>快照</a></p></li>";
        }
    }
    $("#detailsShow").html(detailsShow);
        
    var hitsPerPage = 10;
    if(num!=null) hitsPerPage = parseInt(num);
    
    var pages = 0;
	var currentPage = 1;
	if(hitsLength > hitsPerPage){
	    if(hitsLength%hitsPerPage != 0)
			pages = hitsLength/hitsPerPage + 1;
		else
			pages= hitsLength/hitsPerPage;
	}
	currentPage = start/hitsPerPage + 1;

	var nSpan = 5;

	var minPageNum = currentPage - nSpan;
	var maxPageNum = currentPage + nSpan;

	if(minPageNum < 1){
		minPageNum = 1;
		maxPageNum += nSpan - currentPage + 1;
	}

	if(maxPageNum > pages){
		maxPageNum = pages;
	}

    if(currentPage > 1){
        var newStart = start-hitsPerPage;
        if(newStart<0)newStart = 0;
        pageIndexShow += "<a href='javascript:doSearch("+newStart+","+hitsPerPage+","+clusterIndex+",0)'>上一页</a>";
    }

    for (var iPage = minPageNum; iPage <= maxPageNum; iPage+=1) {
	    if (currentPage == iPage) {
	    	pageIndexShow += "<span>"+iPage+"</span>";
        }
        else {
        	var newStart = start+hitsPerPage*(iPage-currentPage);
        	if(newStart<0)newStart = 0;
        	pageIndexShow += "<a href='javascript:doSearch("+newStart+","+hitsPerPage+","+clusterIndex+",0)'>"+iPage+"</a>";
        }
    }

    if (currentPage < pages) {
    	  var newStart = start+hitsPerPage;
          pageIndexShow += "<a href='javascript:doSearch("+newStart+","+hitsPerPage+","+clusterIndex+",0)'>下一页</a>";
    }
    $("#pageIndexShow").html(pageIndexShow);
}

function showClusters(data){
    var clusters = eval('('+data+')');
    var clustersresult = clusters.Clusters;
    if(clustersresult.length > 0){
    	var resultIndex = clusters.ResultIndex;
        var clusterPages = clusters.ClusterPages;
        alert(clusterPages);
    	var costTime = clusters.CostTime;
    	var costTimeShow = "第"+(resultIndex+1)+"到第"+(resultIndex+clusterPages)+"结果聚类</br>用时" + costTime + "ms";
    	$("#clusterTimeShow").html(costTimeShow);
    	
    	var clustersShow = "";
    	clustersShow += "<li><a href='javascript:doSearch("+0+","+num+","+-1+","+0+")'>所有结果</a></li>";
    	for(var i = 0; i<clustersresult.length; i+=1){
    		var label = clustersresult[i].LabelName;
    		var index = clustersresult[i].ClusterIndex;
    		clustersShow += "<li><a href='javascript:doSearch("+0+","+num+","+index+","+0+")'>"+label+"</a></li>";
    	}
    	$("#clusterShow").html(clustersShow);    
    }
    else{
    	$("#clusterShow").html("没有聚类结果");
    }
}

function showGram(data){
    var gramPre = eval(data);
    var dates = gramPre.Dates;
    var datagram = [];
    for(var i = 0; i < dates.length; i++){
    		var dateInt = dates[i].Date;
    		var sum = dates[i].Sum;
        datagram.push([dateInt,sum]);
    }
    dataindex = datagram.length - 1;
    plot = $.plot($("#placeholder"), [{data: datagram}],
    {
    	bars: { show: true ,align:"center"},
    	grid: { hoverable: true,clickable: true },
      selection: { mode: "x" }
    }
   	);

    $("#placeholder").bind("plotclick", function (event, pos, item) {
    	var tmp = Math.round(pos.x);
    	for(var i = 0; i < datagram.length; i++){
    		  if(tmp == datagram[i][0]){ 	
          if(date == "")
          date = "date:" + tmp;
            else{
              date = date.substring(0,9);
              if(datagram[i][0] < 10)
                date = date + "-0" + datagram[i][0];
              else
                date = date + "-" + datagram[i][0];
          }
          self.location="./searchAjax.jsp?query=" + query + "&prequery=" + prequery + "&date=" + date;
        }
      }
    });

    var preregion = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        var label = "";
        if(date == "")
        label = "Year:";
        else
        label = "Month:";
        var tmp = Math.round(pos.x);
				if(preregion != tmp){
				preregion = tmp;
				var tmpFrom = tmp -0.5;
				var tmpTo = tmp + 0.5;
				//alert(plot);
				if(tmp >= datagram[0][0] && tmp <= datagram[dataindex][0])
				plot.setSelection({x1:tmpFrom,x2:tmpTo});
				for(var i = 0; i < datagram.length; i++){
					if(tmp == datagram[i][0]){
					$("#tooltip").remove();
					showTooltip(pos.pageX, pos.pageY,
                                label + datagram[i][0] + "  Sum:" + datagram[i][1]);
						}
				}
				}
    });
}

function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
}